package my.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Page;
import my.common.Util;
import my.interceptor.Login;
import my.model.Message;
import my.model.User;
import my.service.MessageService;

import java.util.List;

/**
 * Created by Administrator on 2017/4/13 0013.
 */
public class MessageController extends Controller {

    MessageService messageService = new MessageService();

    public void index() {
        list();

    }


    public void list() {
        List<Message> messages = messageService.getAllMessageDetail();
        setAttr("messages", messages);

        renderFreeMarker("list.ftl");
        //TODO:实现留言列表

    }


    public void json() {
        int pageSize = getParaToInt("length", 10);
        int draw = getParaToInt("draw", 1);
        int start = getParaToInt("start", 0);
        int page = start / pageSize;
        if (page == 0) page = 1;
        Page<Message> messagePage = messageService.paginateAllMessageDetail(page, pageSize);
        setAttr("draw", draw);
        setAttr("data", messagePage.getList());
        setAttr("recordsTotal", messagePage.getTotalRow());
        setAttr("recordsFilter", messagePage.getTotalRow());
        setAttr("pages", messagePage.getTotalPage());
        renderJson();
    }

    @Before({Login.class, POST.class})
    public void update() {
        // Message message = getModel(Message.class, true);
        int id = getParaToInt("message.id", -1);
        String content = getPara("message.content", "");
        String title = getPara("message.title", "");

        Message message = new Message();
        if (id != -1)
            message.setId(id);
        if (!content.isEmpty())
            message.setContent(content);
        if (!title.isEmpty())
            message.setTitle(title);

        User loginUser = (User) getSessionAttr("user");
        Message findMessage = Message.dao.findById(id);
        boolean success = false;
        if (loginUser.getId() == findMessage.getUserId()) {
            success = messageService.updateMessage(message);
        }
        String retMessage = success ? "修改成功" : "修改失败";
        renderJson(Util.ajaxJson(success, retMessage));

    }

    @Before(Login.class)
    public void delete() {

        User loginUser = (User) getSessionAttr("user");
        int id = getParaToInt(0, -1);

        boolean success = messageService.deleteMessageById(loginUser.getId(), id);


        renderJson(Util.ajaxJson(success, success ? "删除成功" : "删除失败"));
        //list();
    }


    public void create() {
        //TODO:显示发表留言页面 要求登录后才能留言
        // 提示 @Before(Login.class) 使用拦截器
        renderFreeMarker("create.ftl");
    }


}
